package com.wang.seckill.controller;

import com.wang.seckill.pojo.User;
import com.wang.seckill.service.GoodsService;
import com.wang.seckill.service.UserService;
import com.wang.seckill.vo.GoodsVo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/goods")
public class GoodsController {
    @Resource
    private UserService userService;

    @Resource
    private GoodsService goodsService;

    @Resource
    private RedisTemplate redisTemplate;

    //手动渲染需要的模板解析器
    @Resource
    private ThymeleafViewResolver thymeleafViewResolver;
    //进入商品列表页-db
//    @RequestMapping("/toList")
//    public String toList(Model model, @CookieValue("userTicket") String ticket, HttpServletRequest request, HttpServletResponse response) {
//
//        if (!StringUtils.hasText(ticket)) {
//            return "login";
//        }
//
//        //通过ticket获取session中user
////        User user = (User) session.getAttribute(ticket);
//        User user = userService.getUserByCookie(ticket, request, response);
//        if (null == user) {
//            return "login";
//        }
//
//        model.addAttribute("user", user);
//        model.addAttribute("goodsList", goodsService.findGoodsVo());
//
//        return "goodsList";
//    }
    //使用redis优化
    @RequestMapping(value = "/toList", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toList(Model model, User user, HttpServletRequest request, HttpServletResponse response) {

        if (null == user) {
            return "login";
        }
        //redis获取页面
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html = (String) valueOperations.get("goodsList");
        if (StringUtils.hasText(html)) {
            return html;
        }

        model.addAttribute("user", user);
        model.addAttribute("goodsList", goodsService.findGoodsVo());


        //如果从redis没有获取到页面
        WebContext webContext =
                new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goodsList", webContext);

        if (StringUtils.hasText(html)) {
            //将页面保存到redis，60秒刷新一次
            valueOperations.set("goodsList", html, 60, TimeUnit.SECONDS);
        }

        return html;
    }
    //redis优化
    @RequestMapping(value = "/toDetail/{goodsId}", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toDetail(Model model, User user, @PathVariable Long goodsId, HttpServletRequest request, HttpServletResponse response) {

        if (user == null) {
            return "login";
        }

        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html = (String) valueOperations.get("goodsDetail:" + goodsId);
        if (StringUtils.hasText(html)) {
            return html;
        }

        model.addAttribute("user", user);
        GoodsVo goodsVo = goodsService.findGoodsVoById(goodsId);
        model.addAttribute("goods", goodsVo);

        //返回秒杀剩余时间
        //1.seckillStatus 秒杀状态：0：秒杀未开始，1：秒杀进行中，2：秒杀已结束
        //2.remainSeconds 剩余描述： 》0 ：表示还有多久开始秒杀； 0 ：表示秒杀进行中 -1：秒杀结束

        Date startDate = goodsVo.getStartDate();
        Date endDate = goodsVo.getEndDate();
        Date nowDate = new Date();

        int seckillStatus = 0;
        int remainSeconds = 0;

        if (nowDate.before(startDate)) {
            remainSeconds = (int) (startDate.getTime() - nowDate.getTime()) / 1000;
        } else if (nowDate.after(endDate)) {
            seckillStatus = 2;
            remainSeconds = -1;
        } else {
            seckillStatus = 1;
            remainSeconds = 0;
        }

        model.addAttribute("remainSeconds", remainSeconds);
        model.addAttribute("seckillStatus", seckillStatus);

        WebContext webContext =
                new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goodsDetail", webContext);

        if (StringUtils.hasText(html)) {
            //将页面保存到redis，60秒刷新一次
            valueOperations.set("goodsDetail:" + goodsId, html, 60, TimeUnit.SECONDS);
        }

        return html;

    }

//    @RequestMapping("/toDetail/{goodsId}")
//    public String toDetail(Model model, User user, @PathVariable Long goodsId) {
//
//        if (user == null) {
//            return "login";
//        }
//
//        model.addAttribute("user", user);
//        GoodsVo goodsVo = goodsService.findGoodsVoById(goodsId);
//        model.addAttribute("goods", goodsVo);
//
//        //返回秒杀剩余时间
//        //1.seckillStatus 秒杀状态：0：秒杀未开始，1：秒杀进行中，2：秒杀已结束
//        //2.remainSeconds 剩余描述： 》0 ：表示还有多久开始秒杀； 0 ：表示秒杀进行中 -1：秒杀结束
//
//        Date startDate = goodsVo.getStartDate();
//        Date endDate = goodsVo.getEndDate();
//        Date nowDate = new Date();
//
//        int seckillStatus = 0;
//        int remainSeconds = 0;
//
//        if (nowDate.before(startDate)) {
//            remainSeconds = (int) (startDate.getTime() - nowDate.getTime()) / 1000;
//        } else if (nowDate.after(endDate)) {
//            seckillStatus = 2;
//            remainSeconds = -1;
//        } else {
//            seckillStatus = 1;
//            remainSeconds = 0;
//        }
//
//        model.addAttribute("remainSeconds", remainSeconds);
//        model.addAttribute("seckillStatus", seckillStatus);
//
//        return "goodsDetail";
//    }
}
